/*
 * Description: description of commodity.js
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Jian.Yang
 * Date: 2020/12/22 0:28
 */

import { commodityList } from '../../api/quote/commodity'

const state = {
  commodityCollects: []
}

const getters = {
  getCommodityCollects: state => state.commodityCollects,
  getCommodityCollectsByGcmFunction: state => gcmFunction => {
    if (gcmFunction === 'ALL') {
      return state.commodityCollects
    } else {
      return state.commodityCollects.filter(c => c.gcmFunction === gcmFunction)
    }
  },
  getGcmFunctionByCommodity: state => cm => {
    const commodity = state.commodityCollects.find(c => c.name === cm)
    if (commodity) {
      return commodity.gcmFunction
    } else {
      return ''
    }
  }
}

const mutations = {
  SET_COMMODITY_COLLECTS: (state, commodityCollects) => {
    state.commodityCollects = commodityCollects
  }
}

const actions = {
  initCommodityCollectsLazy({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.commodityCollects.length > 0) {
        resolve()
      } else {
        commodityList({})
          .then(response => {
            commit('SET_COMMODITY_COLLECTS', response.data)
            resolve()
          })
          .catch(err => reject(err))
      }
    })
  },
  initCommodityCollects({ commit }) {
    return new Promise((resolve, reject) => {
      commodityList({})
        .then(response => {
          commit('SET_COMMODITY_COLLECTS', response.data)
          resolve()
        })
        .catch(err => reject(err))
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
